package song.NO_2;

public class addTwoNumbers implements Link{
    private Lianbiao l1 = null;
    private Lianbiao l2 = null;
    private int result = 0;
    public addTwoNumbers(){}
    public addTwoNumbers(final Lianbiao l1s, final Lianbiao l2s){
        this.l1 = l1s;
        this.l2 = l2s;
    }
    public void add(){
        Node head1 = this.l1.head_return().next_return();
        Node head2 = this.l2.head_return().next_return();
        int jinwei = 0, gewei = 0;
        //新建链表头结点
        Node head_new = new Node();
        Node move = head_new;
        head_new.next_set(move);
        while (head1 != null || head2 != null){
            move.next_set(new Node());
            move = move.next_return();
            int beijia = 0, jia = 0;
            if (head1 != null) beijia = head1.num_return();
            if (head2 != null) jia = head2.num_return();
            int node_result = beijia + jia;
            if (node_result >= 10){
                gewei = node_result % 10;
                move.num_set(gewei+jinwei);
                jinwei = 1;
            }
            else {
                move.num_set(node_result+jinwei);
                jinwei = 0;
            }
            if (head1 != null) head1 = head1.next_return();
            if (head2 != null) head2 = head2.next_return();
        }
        if (jinwei == 1){
            move.next_set(new Node(jinwei));
        }
        this.print(head_new);
    }

    @Override
    public void print(Node head) {
        Node move = head.next_return();
        int i = 0;
        while (move != null){
            System.out.println(move.num_return());
            this.result += move.num_return() * (int)Math.pow(10, i);
            move = move.next_return();
            ++i;
        }
        System.out.println(this.result);
    }
}
